<template>
  <div class="coupon-management">
    <!-- 搜索和操作栏 -->
    <el-card class="search-card">
      <el-form :model="searchForm" :inline="true" class="search-form">
        <el-form-item label="券名称">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入券名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="券类型">
          <el-select v-model="searchForm.type" placeholder="请选择券类型" clearable>
            <el-option label="满减券" value="FULL_REDUCTION" />
            <el-option label="折扣券" value="DISCOUNT" />
            <el-option label="立减券" value="DIRECT_REDUCTION" />
            <el-option label="赠品券" value="GIFT" />
            <el-option label="阶梯券" value="LADDER" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="草稿" value="DRAFT" />
            <el-option label="已发布" value="PUBLISHED" />
            <el-option label="已停用" value="STOPPED" />
            <el-option label="已过期" value="EXPIRED" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮 -->
    <el-card class="action-card">
      <div class="action-buttons">
        <el-button type="primary" @click="handleCreate">
          <el-icon><Plus /></el-icon>
          创建优惠券
        </el-button>
        <el-button 
          type="success" 
          :disabled="!selectedRows.length"
          @click="handleBatchPublish"
        >
          <el-icon><Upload /></el-icon>
          批量发布
        </el-button>
        <el-button 
          type="warning" 
          :disabled="!selectedRows.length"
          @click="handleBatchStop"
        >
          <el-icon><Download /></el-icon>
          批量停用
        </el-button>
        <el-button 
          type="danger" 
          :disabled="!selectedRows.length"
          @click="handleBatchDelete"
        >
          <el-icon><Delete /></el-icon>
          批量删除
        </el-button>
      </div>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="tableData"
        @selection-change="handleSelectionChange"
        stripe
        border
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="券名称" min-width="150" />
        <el-table-column prop="type" label="券类型" width="100">
          <template #default="{ row }">
            <el-tag :type="getTypeTagType(row.type)">
              {{ getTypeText(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="value" label="面值" width="100">
          <template #default="{ row }">
            <span v-if="row.type === 'DISCOUNT'">{{ (row.value * 10).toFixed(1) }}折</span>
            <span v-else>¥{{ row.value }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="threshold" label="使用门槛" width="100">
          <template #default="{ row }">
            ¥{{ row.threshold }}
          </template>
        </el-table-column>
        <el-table-column prop="totalStock" label="总库存" width="80" />
        <el-table-column prop="receivedCount" label="已领取" width="80" />
        <el-table-column prop="usedCount" label="已使用" width="80" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="validEndTime" label="有效期" width="120">
          <template #default="{ row }">
            {{ formatDate(row.validEndTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="160">
          <template #default="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="handleView(row)">
              <el-icon><View /></el-icon>
              查看
            </el-button>
            <el-button 
              v-if="row.status === 'DRAFT'"
              size="small" 
              type="primary" 
              @click="handleEdit(row)"
            >
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button 
              v-if="row.status === 'DRAFT'"
              size="small" 
              type="success" 
              @click="handlePublish(row)"
            >
              <el-icon><Upload /></el-icon>
              发布
            </el-button>
            <el-button 
              v-if="row.status === 'PUBLISHED'"
              size="small" 
              type="warning" 
              @click="handleStop(row)"
            >
              <el-icon><Download /></el-icon>
              停用
            </el-button>
            <el-button 
              v-if="row.status === 'DRAFT'"
              size="small" 
              type="danger" 
              @click="handleDelete(row)"
            >
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="pagination.current"
        v-model:page-size="pagination.size"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 券效分析对话框 -->
    <el-dialog
      v-model="analysisDialogVisible"
      title="券效分析"
      width="800px"
    >
      <div v-if="analysisData" class="analysis-content">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-statistic title="总库存" :value="analysisData.totalStock" />
          </el-col>
          <el-col :span="8">
            <el-statistic title="已领取" :value="analysisData.receivedCount" />
          </el-col>
          <el-col :span="8">
            <el-statistic title="已使用" :value="analysisData.usedCount" />
          </el-col>
        </el-row>
        <el-row :gutter="20" style="margin-top: 20px;">
          <el-col :span="12">
            <el-statistic 
              title="领取率" 
              :value="(analysisData.receiveRate * 100).toFixed(2)" 
              suffix="%" 
            />
          </el-col>
          <el-col :span="12">
            <el-statistic 
              title="核销率" 
              :value="(analysisData.useRate * 100).toFixed(2)" 
              suffix="%" 
            />
          </el-col>
        </el-row>
        <el-row style="margin-top: 20px;">
          <el-col :span="24">
            <el-statistic 
              title="总优惠金额" 
              :value="analysisData.totalDiscount" 
              prefix="¥" 
            />
          </el-col>
        </el-row>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getCouponList, 
  deleteCoupon, 
  publishCoupon, 
  stopCoupon, 
  batchOperateCoupons,
  getCouponAnalysis 
} from '@/api'
import { formatDate, formatDateTime } from '@/utils/date'

const router = useRouter()

// 响应式数据
const loading = ref(false)
const tableData = ref([])
const selectedRows = ref([])
const analysisDialogVisible = ref(false)
const analysisData = ref(null)

// 搜索表单
const searchForm = reactive({
  name: '',
  type: '',
  status: ''
})

// 分页数据
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 获取券类型文本
const getTypeText = (type) => {
  const typeMap = {
    'FULL_REDUCTION': '满减券',
    'DISCOUNT': '折扣券',
    'DIRECT_REDUCTION': '立减券',
    'GIFT': '赠品券',
    'LADDER': '阶梯券'
  }
  return typeMap[type] || type
}

// 获取券类型标签类型
const getTypeTagType = (type) => {
  const typeMap = {
    'FULL_REDUCTION': 'success',
    'DISCOUNT': 'warning',
    'DIRECT_REDUCTION': 'danger',
    'GIFT': 'info',
    'LADDER': 'primary'
  }
  return typeMap[type] || ''
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    'DRAFT': '草稿',
    'PUBLISHED': '已发布',
    'STOPPED': '已停用',
    'EXPIRED': '已过期'
  }
  return statusMap[status] || status
}

// 获取状态标签类型
const getStatusTagType = (status) => {
  const statusMap = {
    'DRAFT': 'info',
    'PUBLISHED': 'success',
    'STOPPED': 'warning',
    'EXPIRED': 'danger'
  }
  return statusMap[status] || ''
}

// 获取券列表
const fetchCouponList = async () => {
  loading.value = true
  try {
    const params = {
      current: pagination.current,
      size: pagination.size,
      ...searchForm
    }
    const response = await getCouponList(params)
    tableData.value = response.data.records
    pagination.total = response.data.total
  } catch (error) {
    ElMessage.error('获取券列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  fetchCouponList()
}

// 重置
const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  pagination.current = 1
  fetchCouponList()
}

// 创建券
const handleCreate = () => {
  router.push('/coupon/create')
}

// 编辑券
const handleEdit = (row) => {
  router.push(`/coupon/edit/${row.id}`)
}

// 查看券
const handleView = async (row) => {
  try {
    const response = await getCouponAnalysis(row.id)
    analysisData.value = response.data
    analysisDialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取券效分析失败')
  }
}

// 发布券
const handlePublish = async (row) => {
  try {
    await ElMessageBox.confirm('确定要发布该券吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await publishCoupon(row.id)
    ElMessage.success('发布成功')
    fetchCouponList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('发布失败')
    }
  }
}

// 停用券
const handleStop = async (row) => {
  try {
    await ElMessageBox.confirm('确定要停用该券吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await stopCoupon(row.id)
    ElMessage.success('停用成功')
    fetchCouponList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('停用失败')
    }
  }
}

// 删除券
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该券吗？删除后无法恢复！', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await deleteCoupon(row.id)
    ElMessage.success('删除成功')
    fetchCouponList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 批量发布
const handleBatchPublish = async () => {
  try {
    await ElMessageBox.confirm('确定要批量发布选中的券吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const ids = selectedRows.value.map(row => row.id)
    await batchOperateCoupons({ ids, operation: 'publish' })
    ElMessage.success('批量发布成功')
    fetchCouponList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量发布失败')
    }
  }
}

// 批量停用
const handleBatchStop = async () => {
  try {
    await ElMessageBox.confirm('确定要批量停用选中的券吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const ids = selectedRows.value.map(row => row.id)
    await batchOperateCoupons({ ids, operation: 'stop' })
    ElMessage.success('批量停用成功')
    fetchCouponList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量停用失败')
    }
  }
}

// 批量删除
const handleBatchDelete = async () => {
  try {
    await ElMessageBox.confirm('确定要批量删除选中的券吗？删除后无法恢复！', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const ids = selectedRows.value.map(row => row.id)
    await batchOperateCoupons({ ids, operation: 'delete' })
    ElMessage.success('批量删除成功')
    fetchCouponList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量删除失败')
    }
  }
}

// 选择变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 分页大小变化
const handleSizeChange = (size) => {
  pagination.size = size
  pagination.current = 1
  fetchCouponList()
}

// 当前页变化
const handleCurrentChange = (current) => {
  pagination.current = current
  fetchCouponList()
}

// 组件挂载时获取数据
onMounted(() => {
  fetchCouponList()
})
</script>

<style scoped lang="scss">
.coupon-management {
  .search-card {
    margin-bottom: 20px;
    
    .search-form {
      .el-form-item {
        margin-bottom: 0;
      }
    }
  }
  
  .action-card {
    margin-bottom: 20px;
    
    .action-buttons {
      display: flex;
      gap: 10px;
    }
  }
  
  .table-card {
    .analysis-content {
      .el-row {
        margin-bottom: 20px;
      }
    }
  }
}
</style>
